import React, { useState } from 'react';
import { useForm } from 'react-hook-form';

import { env, regex, urls } from '@/shared/constants';
import Telegram from '@/shared/icons/logo/TelegramCircle.svg';
import { Button, ButtonVariants, Container } from '@/shared/ui';
import { yupResolver } from '@hookform/resolvers/yup';
import cn from 'classnames';
import Image from 'next/image';
import * as yup from 'yup';

import { ColouredInfoBlock } from '../ColouredInfoBlock';
import cs from './Contact.module.scss';

const schema = yup.object().shape({
  name: yup.string().required(),
  email: yup.string().matches(regex.email).required(),
  message: yup.string().required(),
});

export const Contact = () => {
  const [isSent, setIsSent] = useState(false);
  const {
    register,
    handleSubmit,
    formState: { errors },
    reset,
  } = useForm({ resolver: yupResolver(schema) });

  const resetForm = () => {
    reset();
    setIsSent(false);
  };

  const onSubmit = async (data: any) => {
    const fd = new FormData();
    Object.keys(data).forEach((key) => {
      fd.append(key, data[key]);
    });
    try {
      await fetch(`${env.apiUrl}/user/test/send-feedback-unauth-from-landing`, {
        method: 'POST',
        body: fd,
        headers: {
          ContentType: 'multipart/form-data',
        },
      });
      setIsSent(() => true);
    } catch (e) {
      console.log(e);
    }
  };

  return (
    <>
      <h1 className={cn('h1', cs.title)} id="contact">
        Написать нам
      </h1>
      <Container className={cs.container} small>
        <p className={cn('p', cs.desc)}>
          Уделяем внимание каждой мелочи, будем рады интересным предложениям и идеям. Ответим на любые вопросы со
          скоростью света в{' '}
          <Button
            aria-label="Telegram"
            className={cn(cs.link, 'a')}
            data-testid="link-telegram_support"
            href={urls.telegramSupport}
            link
            target="_blank"
          >
            <Image alt="telegram icon" height={24} src={Telegram} width={24} />
            <span>Telegram</span>
          </Button>
        </p>
        {isSent ? (
          <ColouredInfoBlock className={cs.block}>
            <p className="p">Спасибо!</p>
            <p className="p">Мы скоро свяжемся с вами.</p>
            <p className={cn('p', cs.reset)} onClick={resetForm}>
              Заполнить снова
            </p>
          </ColouredInfoBlock>
        ) : (
          <form className={cs.form} onSubmit={handleSubmit(onSubmit)}>
            <input
              className={cn(cs.input, { [cs.error]: errors.name })}
              placeholder="Имя"
              type="text"
              {...register('name')}
            />
            <input
              className={cn(cs.input, { [cs.error]: errors.email })}
              placeholder="Почта"
              type="text"
              {...register('email')}
            />
            <input
              className={cn(cs.input, { [cs.error]: errors.message })}
              placeholder="Сообщение"
              type="text"
              {...register('message')}
            />
            <Button className={cs.button} data-testid="button-submit" type="submit" variant={ButtonVariants.Main}>
              Отправить
            </Button>
          </form>
        )}
      </Container>
    </>
  );
};
